package com.lebang.service.log;

import com.lebang.model.ErrorLogModel;
import com.lebang.service.mongodb.ErrorLogMongodb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Set;

/**
 * @Author: hwq
 * @Date: 2020/4/5 19:01
 * @Version 1.0
 */
@Service
@Slf4j
public class LogService {
    @Autowired
    private ErrorLogMongodb errorLogMongodb;
    public void addLog(Exception ex) {
        log.error("异常",ex);
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attr!=null){
            try {
                HttpServletRequest request = attr.getRequest();
                String uri = request.getRequestURI();
                log.error("该接口请求报错:-------------------->>" + uri + "<<<--------------------------");
                Map<String, String[]> map = request.getParameterMap();
                Set<String> keyset = map.keySet();
                log.error("请求参数为:-------STAR--------->>" + uri + "<<<----------STAR--------------");
                for (String key : keyset) {
                    //5.获取当前key
                    StringBuilder text=new StringBuilder();
                    //6.map.get()根据当前key获取value
                    String[] value = map.get(key);

                    //因为value是String[],所以用循环输出
                    for (String s : value) {
                        text.append(s).append("  ");
                    }
                    log.error("[key : "+key+"]"+"----->"+"[value  :  "+text+"]");
                }
                log.error("请求参数为:-------END--------->>" + uri + "<<<----------END--------------");
                ErrorLogModel model=new ErrorLogModel(request);
                model.setUri(uri);

                 Writer result = new StringWriter();
                 PrintWriter printWriter = new PrintWriter(result);
                 ex.printStackTrace(printWriter);
                //System.out.println("-------END-----"+result.toString());
                model.setEx(result.toString());
                model.setClassName(ex.getClass().getName()+":"+ex.getMessage()+":"+ex.getLocalizedMessage());
                errorLogMongodb.save(model);
            }catch (Exception e){
                log.error("异常",e);
            }

        }
    }
}
